package com.wuwei.elearning.question.controller;

import com.alibaba.fastjson.JSON;
import com.wuwei.elearning.question.model.ChatMessage;
import com.wuwei.elearning.question.model.ChatRequest;
import com.wuwei.elearning.question.model.ChatResponse;
import com.wuwei.elearning.question.service.AiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/elearning/askAi")
@CrossOrigin
@Slf4j
public class AiController {
    
    @Autowired
    private AiService aiService;
    
    /**
     * Endpoint for streaming chat completions (POST)
     * @param request the chat request containing prompt and history
     * @param httpRequest the HTTP request to extract user information
     * @return SSE emitter for streaming response
     */
    @PostMapping(value = "/chat", produces = org.springframework.http.MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChat(
            @RequestBody ChatRequest request, 
            HttpServletRequest httpRequest) {
        
        // If no userId is provided, try to get user from session or token
        if (request.getUserId() == null) {
            // This is a placeholder. In your actual implementation,
            // extract user ID from JWT token, session, or request attribute
            String userId = (String) httpRequest.getAttribute("userId");
            if (userId != null) {
                request.setUserId(userId);
                log.debug("Using user ID from request attributes: {}", userId);
            }
        }
        
        return aiService.streamChatCompletion(request);
    }
    

    
    /**
     * Endpoint for streaming chat completions (GET with query parameters)
     * @param prompt the user's message
     * @param history array of previous messages in JSON format
     * @param userId user ID for caching conversation (optional)
     * @return SSE emitter for streaming response
     */
    @GetMapping(value = "/chat", produces = org.springframework.http.MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChatGet(
            @RequestParam String prompt,
            @RequestParam(required = false) String history,
            @RequestParam(required = false) String userId) {
        
        ChatRequest request = new ChatRequest();
        request.setPrompt(prompt);
        request.setUserId(userId);
        
        if (history != null && !history.isEmpty()) {
            try {
                List<ChatMessage> messages = JSON.parseArray(history, ChatMessage.class);
                request.setHistory(messages);
            } catch (Exception e) {
                log.error("Error parsing chat history: {}", e.getMessage());
                // If parsing fails, default to empty history
                request.setHistory(Collections.emptyList());
            }
        } else {
            request.setHistory(Collections.emptyList());
        }
        
        return aiService.streamChatCompletion(request);
    }
    
    /**
     * Clear cached conversation for a user
     * @param userId the user ID whose conversation should be cleared
     * @return success message
     */
    @DeleteMapping("/conversation/{userId}")
    public ResponseEntity<String> clearConversation(@PathVariable String userId) {
        aiService.cacheConversation(userId, Collections.emptyList());
        return ResponseEntity.ok("Conversation cleared for user: " + userId);
    }
}
